import React, { FC, useState, useEffect } from 'react';
import {
  HistoryTask,
  UserTask,
  TaskItem
} from '@/components/ProcessSteps/interface';
import { TaskStatus } from '@/pages/approval/constants';
import { formatTime } from '@/utils/date';
import styles from './index.module.less';
// import Image from '@/components/Image/TokenImage';
import { Accordion, Steps } from 'antd-mobile-v2';
import classnames from 'classnames';
import Avatar from '../avatar';
const { Panel } = Accordion;
const { Step } = Steps;

interface IProps {
  historyTask: HistoryTask[];
  srvTime?: number;
  renderMode?: string;
  className?: string;
}

const ProcessList: FC<IProps> = (props) => {
  const [historyTask, setHistoryTask] = useState<any[]>([]);
  const [currentTask, setCurrentTask] = useState<number>(0);
  const [activeKey, setActiveKey] = useState<string>('0');

  useEffect(() => {
    const historyTask = props.historyTask || [];
    const index = historyTask?.map((item) => item.nodeStatus).indexOf(0);
    if (index == -1) {
      setCurrentTask(historyTask.length);
    } else {
      setCurrentTask(index);
    }
    if (!historyTask || !historyTask.length) {
      setHistoryTask([]);
      return;
    }
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    let finalHistoryTask: any = [...historyTask];
    // 过滤后端返回的已结束节点
    if (historyTask[historyTask.length - 1].nodeStatus === undefined) {
      finalHistoryTask = historyTask.slice(0, historyTask.length - 1);
    }
    console.log('index------------', index);
    
    // 审批中-需要展示已结束节点
    if (index != -1) {
      finalHistoryTask.push({
        ccUsers: [
          {
            taskStatusName: '结束',
            noAvator: 1
          }
        ]
      });
    }
    setHistoryTask(finalHistoryTask);
  }, [props.historyTask]);

  const renderReason = (useTask: UserTask) => {
    if (!useTask.handlerComment) {
      return null;
    }
    if (useTask.taskStatus === TaskStatus.Agree) {
      return <div className="longText">同意原因：{useTask.handlerComment}</div>;
    }
    if (useTask.taskStatus === TaskStatus.Reject) {
      return <div className="longText">拒绝原因：{useTask.handlerComment}</div>;
    }
    return <div className="longText">{useTask.handlerComment}</div>;
  };

  const renderProcess = (historyItem: HistoryTask) => {
    // console.log('historyItem----{}', historyItem);
    // if (!historyItem.ccUsers) return ;
    const ccUsers = historyItem.ccUsers || [];
    const approveUsers = historyItem.approveUsers?.map((el) => {
      return {
        ...el,
        taskStatusName: '已抄送'
      };
    });

    // activityId: "Activity_1hy2hxw"
    // activityName: "最终确认"
    // approveUsers: [{…}]
    // ccUsers: []
    // nodeStatus: 0

    const tasks = ccUsers.concat(approveUsers || []);
    return tasks.map((taskItem, index) => {
      // console.log('taskItem------------[]', taskItem);

      return (
        <div
          key={taskItem.taskRecordId || index}
          className={styles.processItemWrap}
        >
          <div
            className={classnames(
              styles.userInfo,
              taskItem.noAvator != 1 ? styles.withAvatar : ''
            )}
          >
            {taskItem.noAvator != 1 && (
              <div className={styles.avator}>
                <Avatar name={taskItem.userName} />
              </div>
            )}
            <span className={styles.handlerNameAndStatus}>
              {taskItem.userName}
              {taskItem.taskStatusName && taskItem.userName ? (
                <span className="dot-symbol"></span>
              ) : null}
              {taskItem.taskStatusName}
            </span>
            {props.srvTime && taskItem.handlerTime ? (
              <div className={styles.time}>
                {formatTime(props.srvTime, taskItem.handlerTime)}
              </div>
            ) : null}
          </div>
          <div
            className={classnames(
              styles.desc,
              'print-no-margin',
              taskItem.noAvator != 1 ? styles.withAvatar : ''
            )}
          >
            {renderReason(taskItem as UserTask)}
          </div>
        </div>
      );
    });
  };

  const getStatus = (
    currentNode: any
  ): 'error' | 'finish' | 'wait' | 'process' | undefined => {
    const nodeStatus = currentNode?.nodeStatus;
    console.log('nodeStatus:',nodeStatus,TaskStatus);
    if (
      nodeStatus == TaskStatus.Reject ||
      nodeStatus == TaskStatus.Revert
    ) {
      return 'error';
    }
    if (
      nodeStatus === TaskStatus.Agree ||
     nodeStatus === TaskStatus.Apply ||
     nodeStatus === TaskStatus.Copy
    ) {
      return 'finish';
    }
    if (nodeStatus === TaskStatus.Approvaling) {
      return 'process';
    }
    return 'process';
  };

  const onShowChange = () => {
    if (activeKey === '0') {
      setActiveKey('1');
    } else {
      setActiveKey('0');
    }
  };

  const getStepIcon = (item: any) => {
    console.log('item.nodeStatus:',item.nodeStatus);
    switch (item.nodeStatus) {
      case TaskStatus.Reject:
        return <i className={'icon iconfont'}>&#xe710;</i>;
      case TaskStatus.Revert:
        return (
          <i className={'icon iconfont'} style={{ color: '#DDDDDD' }}>
            &#xe711;
          </i>
        );
      case TaskStatus.Approvaling:
        return (
          <i className={'icon iconfont'} style={{ color: '#1fb860' }}>
            &#xe70e;
          </i>
        );
      case TaskStatus.Agree:
      case TaskStatus.Apply:
      case TaskStatus.Copy:
        return <i className={'icon iconfont'}>&#xe70d;</i>;
      default:
        return (
          <i className={'icon iconfont'} style={{ color: '#DDDDDD' }}>
            &#xe70e;
          </i>
        );
    }
  };
  console.log('historyTask-----------[]', historyTask);
  return (
    <Accordion
      accordion
      className={styles.collapseProcess}
      activeKey={activeKey}
      onChange={onShowChange}
    >
      <Panel header={'审批流程'} key="0">
        {historyTask.length > 0 && (
          <Steps current={currentTask} direction="vertical" size="small">
            {historyTask.map((historyItem, index) => (
              <Step
                key={historyItem.taskDefKey || index}
                title={renderProcess(historyItem)}
                status={getStatus(historyItem)}
                icon={getStepIcon(historyItem)}
              />
            ))}
          </Steps>
        )}
      </Panel>
    </Accordion>
  );
};

export default ProcessList;
